<?php
/**
*
* example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
* 
**/
//halt(EXTEND_PATH."WxPayApi/lib/WxPay.Api.php");
//require_once EXTEND_PATH."WxpayAPI_php/Info.php";

require_once EXTEND_PATH."WxpayAPI_php/php_sdk/lib/WxPay.Api.php";
require_once EXTEND_PATH."WxpayAPI_php/php_sdk/lib/WxPay.Notify.php";
require_once EXTEND_PATH."WxpayAPI_php/php_sdk/example/log.php";
require_once EXTEND_PATH."WxpayAPI_php/php_sdk/lib/WxPay.Data.php";

//初始化日志
$logHandler= new CLogFileHandler(PUBLIC_PATH."static/logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$config = new WxPayConfig();
		$result = WxPayApi::orderQuery($config, $input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	public function NotifyProcess($objData,$config, &$msg){


		$filename = '/home/wwwroot/default/milk_tea_shop/NotifyProcess.log';
		file_put_contents($filename, 'RET:'.json_encode($objData));
		
		$data = $objData->GetValues();
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$order = $this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		return $this->orderNotify($data,$msg);
		
	}
	public function orderNotify($data,&$msg)
	{
		// echo $data['out_trade_no'];
//		$time = time();
		$sysOrder = db('order')->where('order_no','=',$data['out_trade_no'])->find();

		if(!$sysOrder){
		    $msg = "订单不存在于客户系统";
		    return false;
		}
		if(($sysOrder['price'] * 100) != $data['total_fee']){
		    $msg = "订单金额不正确";
		    return false;
		}
		if($sysOrder['transaction_id']){
		    $msg = "此订单已经支付过了";
		    return false;
		}

		$UpOrder = db('order')->where('order_no','=',$data['out_trade_no'])->update([
			'pay_time' =>strtotime($data['time_end']),
			'transaction_id' =>$data['transaction_id'],
//            'is_pay' => 1,
		]);
		if($UpOrder){
		    return true;
		}
		return false;
	}
}


?>